#!coding:utf-8
# vim: tabstop=4 shiftwidth=4 softtabstop=4

"""
System-level utilities and helper functions.
"""

import datetime
import os
import random
import subprocess
import sys
import shlex

import types


    
import socket
from ConfigParser import ConfigParser

TIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"

def die(message, *args):
    print >> sys.stderr, message % args
    sys.exit(1)

def get_host_name():
    return socket.gethostname()

def utcnow():
    return datetime.datetime.now()

def abspath(s):
    return os.path.join(os.path.abspath(os.path.dirname(__file__)), s)


def generate_mac():
    mac = [0x12, 0x03, 0xfe, random.randint(0x00, 0x7f),
           random.randint(0x00, 0xff), random.randint(0x00, 0xff)]
    return ':'.join(map(lambda x: "%02x" % x, mac))


def last_octet(address):
    return int(address.split(".")[-1])


def isotime(at=None):
    if not at:
        at = datetime.datetime.now()
    return at.strftime(TIME_FORMAT)


def format_datetime(s,fmt="%Y-%m-%d %H:%M:%S"):
    #return datetime.strptime(s,fmt)
    return datetime.datetime.strptime(s,fmt)

def load_lottery_conf():
    if os.path.exists("/etc/lottery/lottery.conf"):
        filename = "/etc/lottery/lottery.conf"
    else:
        filename = os.path.join(os.path.dirname(os.path.dirname(__file__)),'lottery.conf')
    c = ConfigParser()
    try:
        c.read(filename)
        
        return dict(c.items('default'))
    except Exception as e:
        print 'can not read config of service : thor.conf',e

def convert_datetime_to_str(dt, fmt="%Y-%m-%d"):
    return dt.strftime(fmt) if dt else ""


def parse_isotime(timestr):
    return datetime.datetime.strptime(timestr, TIME_FORMAT)

def in_period(start,end):
    return start<=datetime.datetime.now()<=end
